package com.Cfeng.XiaohuanChat.controller;

import com.Cfeng.XiaohuanChat.domain.CaptchaCodeVo;
import com.Cfeng.XiaohuanChat.domain.KaptchaConstant;
import com.Cfeng.XiaohuanChat.domain.Resp;
import com.Cfeng.XiaohuanChat.entity.ChatUser;
import com.Cfeng.XiaohuanChat.service.ChatUserService;
import com.Cfeng.XiaohuanChat.service.FileStoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/8/7
 */

@RestController
@RequestMapping("/login")
@RequiredArgsConstructor
public class LoginController {

    //注册使用的，和安全的有区别
    private final ChatUserService userService;

    //使用文件上传业务
    private final FileStoreService fileStoreService;

    //可以不用使用@RequestBody，本来就会注入到同名属性
    @PostMapping("/register")
    public Resp<ChatUser> toRegister(HttpSession httpSession, @RequestParam("file") MultipartFile file, @RequestParam("kaptchaCode") String kaptchaCode, ChatUser chatUser) throws IllegalAccessException {
        //先调用验证码
        CaptchaCodeVo codeInSession = (CaptchaCodeVo) httpSession.getAttribute(KaptchaConstant.CAPTCHA_SESSION_KEY);
        if(StringUtils.isEmpty(kaptchaCode)) {
            return Resp.failed("验证码不能为空");
        }
        if(codeInSession == null) {
            return Resp.failed("验证码不存在");
        }
        if(codeInSession.isExpired()) {
            //从用户session中删除
            httpSession.removeAttribute(KaptchaConstant.CAPTCHA_SESSION_KEY);
            return Resp.failed("验证码已过期");
        }
        if(! kaptchaCode.equalsIgnoreCase(codeInSession.getCode())) {
            return Resp.failed("验证码错误");
        }
        if(Objects.isNull(chatUser.getUserName())) return Resp.failed("用户名不能为空,请重新注册");
        //用户密码加密
        String password = chatUser.getUserPwd();
        String newPwd =  BCrypt.hashpw(password,BCrypt.gensalt());
        chatUser.setUserPwd(newPwd);
        //文件上传到服务器
        String headerImgName =  fileStoreService.uploadFile(file);
        //文件上传后注册用户
        chatUser.setUserHeaderImg(headerImgName);
        System.out.println(chatUser);
        //持久化,整个user一起
        userService.addOrUpdateUser(chatUser);
        return Resp.ok(chatUser);
    }
}
